package org.example.blog.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

public class SecurityUtil {
    public static String encrypt(String password){
        //每次生成内容不同，固定32位的盐
        String salt = UUID.randomUUID().toString().replace("-","");
        //最终密码=md5（盐值+原始密码)
        String finalPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        return salt+finalPassword;
    }
    //密码验证
    public static boolean verify(String password, String finalPassword){
        if (!StringUtils.hasLength(password) || !StringUtils.hasLength(finalPassword)){
            return false;
        }
        if (finalPassword.length() != 64){
            return false;
        }
        //加盐
        String salt = finalPassword.substring(0, 32);
        String securityPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        return (salt + securityPassword).equals(finalPassword);
    }
}
